/*
 * HttpRestServer.cpp
 *
 *  Created on: 2022-05-08
 *      Author: chuanjiang.zh
 */

#include "HttpRestServer.h"
#include "HttpServiceUtil.h"
#include "TStringUtil.h"
#include "TProperties.h"
#include "ErrorText.h"
#include "Socket.h"
#include "HttpServiceUtil.h"


HttpRestServer::HttpRestServer()
{
	m_server = HttpFactory::makeServer();
    m_auth->setExpiration(60 * 60);
}

HttpRestServer::~HttpRestServer()
{
	m_server.reset();
}

bool HttpRestServer::start(int port)
{
	setupUri();

	return m_server->start("", port, this);
}

void HttpRestServer::stop()
{
	m_server->stop();
}

bool HttpRestServer::isStarted()
{
	return m_server->isStarted();
}

HttpServerPtr HttpRestServer::getServer()
{
	return m_server;
}

void HttpRestServer::setupUri()
{
    
}

bool HttpRestServer::bodyAsJson(HttpRequest& request, Json::Value& json)
{
	return HttpServiceUtil::bodyAsJson(request, json);
}

bool HttpRestServer::parseJson(const char* str, size_t len, Json::Value& json)
{
    return HttpServiceUtil::parseJson(str, len, json);
}

int HttpRestServer::setResult(const Json::Value& json, HttpResult& result)
{
    return setResultData(result, json);
}

int HttpRestServer::setResult(HttpResult& result, const Json::Value& json)
{
    return setResultData(result, json);
}

int HttpRestServer::setResult(HttpResult& result, const db::JsonList& jsonList)
{
    Json::Value json(Json::arrayValue);
    db::DbJsonConnection::toJson(jsonList, json);

    return setResult(result, json);
}

int HttpRestServer::setResult(HttpResult& result, int offset, int limit, int total, const db::JsonList& jsonList)
{
    Json::Value json;
    db::DbJsonConnection::toJson(offset, limit, total, jsonList, json);
    return setResult(result, json);
}

int HttpRestServer::setResult(HttpResult& result, bool got)
{
    int rc = got ? 0 : EIO;
    return setError(rc, result);
}

int HttpRestServer::setResultData(HttpResult& result, const Json::Value& json)
{
    //Json::Value value(Json::objectValue);
    //value["code"] = 0;
    //value["data"] = json;

    result.content = json.toStyledString();
    return 0;
}


int HttpRestServer::query(db::DbJsonConnection& conn, const std::string& sql, HttpResult& result)
{
    Json::Value json(Json::objectValue);
    if (conn.query(sql, json))
    {
        return setResultData(result, json);
    }
    else
    {
        return setError(ENOENT, result);
    }
}

int HttpRestServer::querySome(db::DbJsonConnection& conn, const std::string& sql, HttpResult& result)
{
    bool got = false;
    Json::Value json(Json::arrayValue);
    if (conn.querySome(sql, json))
    {
        return setResultData(result, json);
    }
    else
    {
        return setResultData(result, Json::Value(Json::arrayValue));
    }
}

int HttpRestServer::execute(db::DbJsonConnection& conn, const std::string& sql, HttpResult& result)
{
    bool got = conn.execute(sql);
    return setResult(result, got);
}

